let PENDING = Symbol('PENDING');
let RESOLVED = Symbol('RESOLVED');
let REJECTED = Symbol('REJECTED');
class NewPromise {
    #status = PENDING;
    #value = undefined;
    #reason = undefined;
    #onResolvedCallbacks = [];
    #onRejectedCallbacks = [];
    constructor(executor) {
        let resolve = (value) => {
            if (this.#status == PENDING) {
                this.#value = value;
                this.#status = RESOLVED;
                this.#onResolvedCallbacks.forEach(fn => fn())
            }
        }
        let reject = (reason) => {
            if (this.#status == PENDING) {
                this.#reason = reason;
                this.#status = REJECTED;
                this.#onRejectedCallbacks.forEach(fn => fn())
            }
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }
    then(onfullfield, onrejected) {
        if (this.#status == RESOLVED) {
            onfullfield(this.#value)
        }
        if (this.#status == REJECTED) {
            onrejected(this.#reason)
        }
        // 如果是异步先订阅
        if (this.#status == PENDING) {
            this.#onResolvedCallbacks.push(() => {
                onfullfield(this.#value)
            })
            this.#onRejectedCallbacks.push(() => {
                onrejected(this.#reason)
            })
        }
    }

    static resolve(value) {
        return new NewPromise((resolve) => {
            resolve(value)
        })
    }
    static all(promises = []) {
       /*  let value = [],
            count = 0;
        return new NewPromise((resolve, reject) => {
            promises.forEach((promise, index) => {
                if (++count == promise.length) {
                    console.log(value);
                    resolve(value)
                    
                }
            })
        }) */
    }
}
new NewPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('哈哈哈')
    }, 1000);
}).then(res => {
    console.log(res);
}, err => {
    throw err
})
